<?php

namespace api\web\controller;


use api\web\model\AdminModel;
use api\web\model\SmsCodeModel;
use api\web\validate\AdminValidate;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class AdminController extends RestBaseController
{
    //注册
    public function register(Request $request)
    {
        $data = $request->param();
        $validate = new AdminValidate();
        $val = $validate->scene('register')->check($data);
        if (!$val) {
            $this->error($validate->getError());
        }

        //验证验证码
        CheckSmsCode($data['mobile'], $data['code']);
        //入库
        $res = AdminModel::create($data);
        if($res)
        {
            $this->success('注册成功');
        }else{
            $this->error('注册失败');
        }
    }

    //登录api
    public function login(Request $request)
    {
        $mobile = $request->param('mobile');
        $code = $request->param('code');

        if(empty($mobile))
        {
            $this->error('手机号码不能为空');
        }
        if(empty($code)){
            $this->error('验证码不能为空');
        }
        $res = AdminModel::where('mobile','=',$mobile)
            ->find();
        if(empty($res))
        {
            $this->error('手机号错误');
        }
        $sms = SmsCodeModel::where('mobile','=',$mobile)
            ->find();
        if(CheckSmsCode($mobile, $sms['code']))
        {
            $token = sendToken($res['id'],$mobile);
            $this->success(
                '登录成功',
                [
                    'data'=>$token
                ]
            );
        }else{
            $this->error('登录失败');
        }
    }
    public function SentCode(Request $request)
    {
        $mobile = $request->param('mobile');
        //发送验证码
        sendAliSms($mobile);
    }
}